using System;
using System.Collections.Generic;

namespace Ioc.Kernel
{
    public class ComponentSelector : IComponentSelector
    {

        private readonly IDictionary<ContainerKey, ComponentModel> components;

        /// <summary>
        /// Initializes a new instance of the <see cref="Resolver"/> class.
        /// </summary>
        /// <param name="components">The components.</param>
        public ComponentSelector(IDictionary<ContainerKey, ComponentModel> components)
        {
            this.components = components;
        }

        /// <summary>
        /// Gets the component.
        /// </summary>
        /// <param name="componentName">Name of the component.</param>
        /// <param name="serviceType">Type of the service.</param>
        /// <returns></returns>
        public ContainerKey GetComponent(Type serviceType, string componentName)
        {
            return componentName != string.Empty
                       ? GetComponentByName(componentName)
                       : GetComponentByService(serviceType);
        }

        /// <summary>
        /// Gets the component by its identificator.
        /// </summary>
        /// <param name="componentName">Name of the component.</param>
        /// <returns></returns>
        private ContainerKey GetComponentByName(string componentName)
        {
            foreach (var containerKey in components.Keys)
            {
                if (containerKey.ComponentName == componentName)
                {
                    return containerKey;
                }
            }
            return null;
        }

        /// <summary>
        /// Gets the first registerd components by service type.
        /// </summary>
        /// <param name="serviceType">Type of the service.</param>
        /// <returns></returns>
        private ContainerKey GetComponentByService(Type serviceType)
        {
            foreach (var containerKey in components.Keys)
            {
                if (containerKey.ComponentService == serviceType)
                {
                    return containerKey;
                }
            }
            return null;
        }
    }
}